#include "taskManager.h"

#include <stdexcept>


TaskManager::TaskManager(std::unique_ptr<DataStore> dataStore)
    : dataStore(std::move(dataStore)), nextId(1) {
    loadTasks();
    // 设置下一个可用的ID
    if (!tasks.empty()) {
        auto maxId = std::max_element(tasks.begin(), tasks.end(),
            [](const Task& a, const Task& b) { return a.getId() < b.getId(); });
        nextId = maxId->getId() + 1;
    }
}

int TaskManager::addTask(const std::string& description, Priority priority, const std::string& dueDate) {
    Task newTask(nextId++, description, priority, dueDate);
    tasks.push_back(newTask);
    saveTasks();
    return newTask.getId();
}

bool TaskManager::deleteTask(int id) {
    auto it = findTaskById(id);
    if (it != tasks.end()) {
        tasks.erase(it);
        saveTasks();
        return true;
    }
    return false;
}

std::vector<Task> TaskManager::getAllTasks() const {
    return tasks;
}

bool TaskManager::updateTaskDescription(int id, const std::string& newDescription) {
    auto it = findTaskById(id);
    if (it != tasks.end()) {
        it->setDescription(newDescription);
        saveTasks();
        return true;
    }
    return false;
}

bool TaskManager::updateTaskPriority(int id, Priority newPriority) {
    auto it = findTaskById(id);
    if (it != tasks.end()) {
        it->setPriority(newPriority);
        saveTasks();
        return true;
    }
    return false;
}

bool TaskManager::updateTaskDueDate(int id, const std::string& newDueDate) {
    auto it = findTaskById(id);
    if (it != tasks.end()) {
        it->setDueDate(newDueDate);
        saveTasks();
        return true;
    }
    return false;
}

void TaskManager::saveTasks() {
    dataStore->save(tasks);
}

void TaskManager::loadTasks() {
    tasks = dataStore->load();
}

std::vector<Task>::iterator TaskManager::findTaskById(int id) {
    return std::find_if(tasks.begin(), tasks.end(),
        [id](const Task& task) { return task.getId() == id; });
}